package org.itzheng.itplayer.player

import android.app.Service
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.itzheng.and.activity.ItActivity
import org.itzheng.itplayer.R
import org.itzheng.itplayer.bean.VideoInfo
import org.itzheng.itplayer.data.DataVideoPlay
import kotlin.collections.ArrayList


/**
 * Title:播放器<br></br>
 * Description: <br></br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2020-8-6.
 */
class VideoPlayActivity : ItActivity() {
    private val TAG = "VideoPlayActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.w(TAG, "onCreate ")
//        hideSystemUI()
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        setContentView(R.layout.activity_video_play_container)
        initView()
    }

    private var mPosition = 0;
    var mItems: ArrayList<VideoInfo>? = null
    private fun initView() {
        mItems = getVideoList(intent)
        mPosition = getPosition(intent);
        if (mItems == null || mItems!!.size < mPosition) {
            showToast("数据错误")
            return
        }
        playVideo(mItems!!, mPosition)
    }

    private fun playVideo(mItems: ArrayList<VideoInfo>, position: Int) {
        val item: VideoInfo = mItems.get(position)
        val fragment = VideoPlayFragment.newInstance(item.fPath!!, item.fTitle!!)
        fragment.setOnCompletionListener {
            //播放结束的监听，这个用于自动播放下一部
            if (position < mItems.size - 1) {
                mPosition++
                playVideo(mItems, mPosition);
            }
        }
        supportFragmentManager.beginTransaction()
                .replace(R.id.container, fragment)
                .commitAllowingStateLoss()
    }

    override fun onResume() {
        super.onResume()
        hideSystemUI()
    }

    override fun onStop() {
        super.onStop()
        //将记录保存
        GlobalScope.launch(Dispatchers.IO) {
            DataVideoPlay.saveLastList(mItems, mPosition)
        }
    }

    /**
     * 设置音量
     * 大于0就是增加
     * 小于等于0就是变小
     */
    private fun setVolume(volume: Int) {
        val audioManager = getSystemService(Service.AUDIO_SERVICE) as AudioManager
        if (volume > 0) {
            //调高声音
// AudioManager.FLAG_SHOW_UI
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI)
        } else {
            //调低声音
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI)
        }

    }

    /**
     * 设置屏幕亮度
     * 0 最暗
     * 1 最亮
     */
    private fun setBrightness(brightness: Float) {
        val lp = window.attributes
        lp.screenBrightness = lp.screenBrightness + brightness / 255.0f
        if (lp.screenBrightness > 1) {
            lp.screenBrightness = 1f
        } else if (lp.screenBrightness < 0.1) {
            lp.screenBrightness = 0.1.toFloat()
        }
        window.attributes = lp
//        val sb = lp.screenBrightness
//        brightnessTextView.setText(Math.ceil(sb * 100.toDouble()) as Int.toString() + "%")
    }

    private var startX = 0;
    private var startY = 0
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = event.x.toInt()
                startY = event.y.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
                if (startX == 0) {
                    startX = event.x.toInt()
                }
                if (startY == 0) {
                    startY = event.y.toInt()
                }
                val screenWidth: Int = window.decorView.getWidth()
                Log.w(TAG, "screenWidth:${screenWidth} ");
                val endY = event.y
                Log.w(TAG, "startX:${startX}, ");
                Log.w(TAG, "startY:${startY}, endY:${endY}");
                //最顶部为0，最底部为屏幕高度，往上数值越来越小，往下数值越来越大
                val distanceY = startY - endY
                if (startX > (screenWidth - screenWidth / 3)) {//右边，处理音量
                    val FLING_MIN_DISTANCE = 10
                    if (distanceY > FLING_MIN_DISTANCE) {
                        //声音变大
                        startY = 0;
                        setVolume(1)
                    } else if (Math.abs(distanceY) > FLING_MIN_DISTANCE) {
                        //说明是往下滑动，声音变小
                        startY = 0;
                        setVolume(0)
                    }
                } else if (startX < screenWidth / 3) {//左边，处理亮度
                    val FLING_MIN_DISTANCE = 0.5
                    val FLING_MIN_VELOCITY = 0.5
                    if (distanceY > FLING_MIN_DISTANCE && Math.abs(distanceY) > FLING_MIN_VELOCITY) {
                        setBrightness(10f)
                    }
                    if (distanceY < FLING_MIN_DISTANCE && Math.abs(distanceY) > FLING_MIN_VELOCITY) {
                        setBrightness(-10f)
                    }
                }
            }
            MotionEvent.ACTION_UP -> {
                //放手
                startX = 0
                startY = 0
            }
        }
        return super.onTouchEvent(event)
    }


    /**
     * 全屏
     */
    private fun hideSystemUI() {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                )
    }

    companion object {
        private val KEY_LIST_VIDEO_INFO: String? = "KEY_LIST_VIDEO_INFO"
        private const val KEY_INT_POSITION = "KEY_INT_POSITION"

        @JvmStatic
        fun startActivity(activity: FragmentActivity, videoList: ArrayList<VideoInfo>?, position: Int) {
            val intent = Intent(activity, VideoPlayActivity::class.java)
            intent.putExtra(KEY_LIST_VIDEO_INFO, videoList)
            intent.putExtra(KEY_INT_POSITION, position)
            activity.startActivity(intent)
        }

        private fun getVideoList(intent: Intent): ArrayList<VideoInfo>? {
            val obj = intent.getSerializableExtra(KEY_LIST_VIDEO_INFO) ?: return null;
            return obj as ArrayList<VideoInfo>
        }

        private fun getPosition(intent: Intent): Int {
            return intent.getIntExtra(KEY_INT_POSITION, 0)
        }
    }
}